import { defineStore } from "pinia";
import { ref, reactive, watch } from "vue";
import {
  tenantUpdateToken,
  tenantList,
} from "@/api/user";
import { useTokenStore } from "../token";

const useUserStore = defineStore(
  // 唯一ID
  "user",
  () => {
    const isLogin = reactive({
      value: uni.getStorageSync("token").value ? 1 : 0,
      popShow: false,
    });
    const initialUserInfo = {
      nickName: "Hi, 欢迎进入~",
      phoneNum: "",
      memberId: "",
      customerId: "",
      avatarUrl: "http://51-jzt-dev.oss-cn-hangzhou.aliyuncs.com/miniapp/default-avatar.png",
      residence: "",
    };

    const initialTenant = {
      value: "", // 租户id 登录时保存
      currentTenant: "",
      option: [],
    };
    // 初始化 reactive 对象
    const userInfo = reactive({ ...initialUserInfo });
    const tenant = reactive({ ...initialTenant });
    // 创建重置函数
    function resetUserInfoAndTenant() {
      Object.assign(userInfo, initialUserInfo);
      Object.assign(tenant, initialTenant);
    }
    // 获取租户列表， 【我的】页面顶部切换
    const updateToken = async () => {
      const result = await tenantUpdateToken({
        tenantId: uni.getStorageSync("tenantId") || tenant.value,
      });
      return result;
    };
    const getTenantList = async () => {
      tenant.value = uni.getStorageSync("tenantId");
      try {
        const result = await tenantList({
          tenantId: uni.getStorageSync("tenantId"),
        });
        if (result?.code == 200) {
          const data = result.data;
          tenant.option = data.map((item) => {
            tenant.currentTenant =
              item.tenantId == tenant.value ? item.tenantName : "";
            return {
              value: item.tenantId,
              label: item.tenantName,
            };
          });
        }
      } catch (error) {
        console.log("租户列表接口报错", error);
      }
    };
    const setData = (data) => {
      const { token, expiresIn, tenantId, tenantName } = data;
      const tokenStore = useTokenStore();
      tokenStore.setCookie("token", token, expiresIn);
      Object.assign(userInfo, data);
      uni.setStorageSync("userInfo", userInfo);
      uni.setStorageSync("tenantId", tenantId);
      tenant.value = tenantId;
      tenant.currentTenant = tenantName;
      isLogin.value = 1;
      if (tenantId) {
        getTenantList();
      }
    };

    return {
      isLogin,
      userInfo,
      tenant,
      updateToken,
      getTenantList,
      setData,
      resetUserInfoAndTenant,
    };
  }
);

export default useUserStore;
